import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { RootState } from '@/app/store'
import { getCategory1, getCategory2, getCategory3 } from '@api/category'
import type { CategoryModel } from '@api/category'
export const getCategory1Async = createAsyncThunk(
  "category/getCategory1Async",
  () => getCategory1()
)

export const getCategory2Async = createAsyncThunk(
  "category/getCategory2Async",
  (category1Id: number) => getCategory2(category1Id)
)

export const getCategory3Async = createAsyncThunk(
  "category/getCategory3Async",
  (category2Id: number) => getCategory3(category2Id)
)

const initialState = {
  category1List: [] as CategoryModel[],
  category2List: [] as CategoryModel[],
  category3List: [] as CategoryModel[],
  category1Id: 0,
  category2Id: 0,
  category3Id: 0,
}

const categorySlice = createSlice({
  name: "category",
  initialState,
  reducers: {
    setCategory1Id(state, action) {
      console.log('category1Id', action.payload)
      state.category1Id = action.payload
      state.category2List = []
      state.category3List = []
      state.category2Id = 0
      state.category3Id = 0
    },
    setCategory2Id(state, action) {
      console.log('category2Id', action.payload)
      state.category2Id = action.payload
      state.category3List = []
      state.category3Id = 0
    },
    setCategory3Id(state, action) {
      console.log('category3Id', action.payload)
      state.category3Id = action.payload
    }
  },
  extraReducers: (builder) =>
    builder
      .addCase(getCategory1Async.fulfilled, (state, action) => {
        const category1List = action.payload
        state.category1List = category1List
      })
      .addCase(getCategory2Async.fulfilled, (state, action) => {
        const category2List = action.payload
        state.category2List = category2List
      })
      .addCase(getCategory3Async.fulfilled, (state, action) => {
        const category3List = action.payload
        state.category3List = category3List
      })
})

// 将redux模块的reducer函数暴露出去,汇总
export default categorySlice.reducer;

// 向外暴露用于读取当前模块的
export const selectCategory = (state: RootState) => state.category;

export const { setCategory1Id, setCategory2Id, setCategory3Id } = categorySlice.actions